package org.brownflat.lighthouse.util;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.util.StopWatch;

/**
 * <p>&copy Rupert Jones 2012</p>
 *
 * @author rup
 */
public class MethodProfiler {
    private final static Logger LOG = Logger.getLogger(MethodProfiler.class);

    /**
     * Intercepts methods that declare com.company.project.util.aop.profiler.Profile and prints out the time it takes to complete
     * @param joinPoint proceeding join point
     * @return the intercepted method returned object
     * @throws Throwable in case something goes wrong in the actual method call
     */
    public Object profileMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        StopWatch clock = new StopWatch("lighthouse-profiling");
        clock.setKeepTaskList(true);
        try {
            try {
                clock.start(joinPoint.toShortString());
                return joinPoint.proceed();
            } finally {
                clock.stop();
                LOG.info(clock.prettyPrint());
            }
        }
        catch (Throwable t) {
            LOG.error("Interceptor caught error: " + t, t);
            throw t;
        }
    }
}
